import { ElMessage } from 'element-plus';
import { reactive, ref } from 'vue';
var g_iWndIndex = 0;
//所有窗体
const uniqueNumbers = new Set();

//通道列表
export const channelValue = ref();
export const channels = reactive([]);

export const percentage = ref(0);

export const searchData = reactive([]);

const showCBInfo = (msg) => {
  if (msg.includes('失败')) {
    ElMessage.error(msg);
  } else {
    ElMessage.success(msg);
  }
};

// PTZ控制 9为自动，1,2,3,4,5,6,7,8为方向PTZ
var g_bPTZAuto = false;
export const mouseDownPTZControl = (iPTZIndex) => {
  var oWndInfo = WebVideoCtrl.I_GetWindowStatus(g_iWndIndex),
    bZeroChannel = false, //是否是0 通道
    iPTZSpeed = 1; //速度

  if (bZeroChannel) {
    // 零通道不支持云台
    return;
  }

  if (oWndInfo != null) {
    if (9 == iPTZIndex && g_bPTZAuto) {
      iPTZSpeed = 0; // 自动开启后，速度置为0可以关闭自动
    } else {
      g_bPTZAuto = false; // 点击其他方向，自动肯定会被关闭
    }

    WebVideoCtrl.I_PTZControl(iPTZIndex, false, {
      iPTZSpeed: iPTZSpeed,
      success: function (xmlDoc) {
        if (9 == iPTZIndex && g_bPTZAuto) {
          // showCBInfo(oWndInfo.szDeviceIdentify + " 停止云台成功！");
        } else {
          // showCBInfo(oWndInfo.szDeviceIdentify + " 开启云台成功！");
        }
        if (9 == iPTZIndex) {
          g_bPTZAuto = !g_bPTZAuto;
        }
      },
      error: function (oError) {
        showCBInfo(oWndInfo.szDeviceIdentify + ' 开启云台失败！' + oError.errorCode + oError.errorMsg);
      },
    });
  }
};

export const getWindowStatus = (index) => {
  return WebVideoCtrl.I_GetWindowStatus(index ? g_iWndIndex : 0);
};

// 打开声音
export const clickOpenSound = () => {
  var oWndInfo = WebVideoCtrl.I_GetWindowStatus(g_iWndIndex);
  if (oWndInfo != null) {
    var allWndInfo = WebVideoCtrl.I_GetWindowStatus();
    // 循环遍历所有窗口，如果有窗口打开了声音，先关闭
    for (var i = 0, iLen = allWndInfo.length; i < iLen; i++) {
      oWndInfo = allWndInfo[i];
      if (oWndInfo.bSound) {
        WebVideoCtrl.I_CloseSound(oWndInfo.iIndex);
        break;
      }
    }

    WebVideoCtrl.I_OpenSound().then(
      () => {
        console.log(oWndInfo.szDeviceIdentify + ' ' + '打开声音成功！');
      },
      (oError) => {
        var szInfo = ' 打开声音失败！';
        showCBInfo(oWndInfo.szDeviceIdentify + szInfo + oError);
      },
    );
  }
};

// 关闭声音
export const clickCloseSound = () => {
  var oWndInfo = WebVideoCtrl.I_GetWindowStatus(g_iWndIndex);
  if (oWndInfo != null) {
    WebVideoCtrl.I_CloseSound().then(
      () => {
        showCBInfo(oWndInfo.szDeviceIdentify + ' ' + '关闭声音成功！');
      },
      (oError) => {
        var szInfo = ' 关闭声音失败！';
        showCBInfo(oWndInfo.szDeviceIdentify + szInfo + oError);
      },
    );
  }
};

// 窗口分割数
export const changeWndNum = (iType) => {
  if ('1*2' === iType || '2*1' === iType) {
    WebVideoCtrl.I_ArrangeWindow(iType).then(
      () => {
        console.log('窗口分割成功！');
      },
      (oError) => {
        var szInfo = '窗口分割失败！';
        console.log(szInfo + oError.errorMsg);
      },
    );
  } else {
    iType = parseInt(iType, 10);
    WebVideoCtrl.I_ChangeWndNum(iType).then(
      () => {
        console.log('窗口分割成功！');
      },
      (oError) => {
        var szInfo = '窗口分割失败！';
        console.log(szInfo + oError.errorMsg);
      },
    );
  }
};

// 方向PTZ停止
export const mouseUpPTZControl = () => {
  var oWndInfo = WebVideoCtrl.I_GetWindowStatus(g_iWndIndex);

  if (oWndInfo != null) {
    WebVideoCtrl.I_PTZControl(1, true, {
      success: function (xmlDoc) {
        // showCBInfo(oWndInfo.szDeviceIdentify + " 停止云台成功！");
      },
      error: function (oError) {
        showCBInfo(oWndInfo.szDeviceIdentify + ' 停止云台失败！' + oError.errorMsg);
      },
    });
  }
};

// 格式化时间
export const dateFormat = (oDate, fmt) => {
  if (oDate == '') {
    return '';
  }
  var o = {
    'M+': oDate.getMonth() + 1, //月份
    'd+': oDate.getDate(), //日
    'h+': oDate.getHours(), //小时
    'm+': oDate.getMinutes(), //分
    's+': oDate.getSeconds(), //秒
    'q+': Math.floor((oDate.getMonth() + 3) / 3), //季度
    S: oDate.getMilliseconds(), //毫秒
  };
  if (/(y+)/.test(fmt)) {
    fmt = fmt.replace(RegExp.$1, (oDate.getFullYear() + '').substr(4 - RegExp.$1.length));
  }
  for (var k in o) {
    if (new RegExp('(' + k + ')').test(fmt)) {
      fmt = fmt.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ('00' + o[k]).substr(('' + o[k]).length));
    }
  }
  return fmt;
};

// 初始化插件参数及插入插件
export const init = (pluginName) => {
  WebVideoCtrl.I_InitPlugin({
    bWndFull: true, //是否支持单窗口双击全屏，默认支持 true:支持 false:不支持
    iWndowType: 1,
    cbSelWnd: function (xmlDoc) {
      g_iWndIndex = parseInt($(xmlDoc).find('SelectWnd').eq(0).text(), 10);
      console.log('cbSelWnd' + $(xmlDoc).find('SelectWnd').eq(0).text());
      uniqueNumbers.add(g_iWndIndex);
      console.log(g_iWndIndex);
    },
    cbDoubleClickWnd: function () {
      console.log('cbDoubleClickWnd');
    },
    cbEvent: (iEventType, iParam1) => {
      if (2 == iEventType) {
        // 回放正常结束
        console.log('窗口' + iParam1 + '回放结束！');
      } else if (-1 == iEventType) {
        console.log('设备' + iParam1 + '网络错误！');
      }
    },
    cbInitPluginComplete: function () {
      WebVideoCtrl.I_InsertOBJECTPlugin(pluginName ? pluginName : 'divPlugin').then(
        () => {
          // 检查插件是否最新
          WebVideoCtrl.I_CheckPluginVersion().then((bFlag) => {
            console.log('bFlag-------------', bFlag);
            if (bFlag) {
              ElMessage.error('检测到新的插件版本，双击开发包目录里的HCWebSDKPlugin.exe升级！');
            } else {
              console.log('初始化成功');
              changeWndNum(2);
              return true;
            }
          });
        },
        () => {
          console.log('插件初始化失败，请确认是否已安装插件；如果未安装，请双击开发包目录里的HCWebSDKPlugin.exe安装！');
          return false;
        },
      );
    },
  });
};
// 抓图
export const capturePicData = (type) => {
  var oWndInfo = WebVideoCtrl.I_GetWindowStatus(g_iWndIndex);
  if (oWndInfo != null) {
    WebVideoCtrl.I_CapturePicData().then(
      (res) => {
        data.img = 'data:image/jpeg;base64,' + res;
        ElMessage.success('抓图成功');
      },
      function () {},
    );
  }
};

//
export const destroy = () => {
  try {
    WebVideoCtrl.I_DestroyPlugin();
    g_iWndIndex = 0;
    console.log('成功销毁插件');
  } catch (err) {
    console.log('销毁插件异常' + err);
  }
};

// 销毁插件
export const destroyPlugin = (data) => {
  WebVideoCtrl.I_Logout(`${data.ip}_${data.port}`).then(
    () => {
      console.log('退出成功');
      WebVideoCtrl.I_DestroyPlugin();
      g_iWndIndex = 0;
    },
    () => {
      console.log('退出失败！');
    },
  );
};

// 获取设备信息
export const clickGetDeviceInfo = (data) => {
  var szDeviceIdentify = `${data.ip}_${data.port}`;

  if (null == szDeviceIdentify) {
    return;
  }

  WebVideoCtrl.I_GetDeviceInfo(szDeviceIdentify, {
    success: function (xmlDoc) {
      var arrStr = [];
      arrStr.push('设备名称：' + $(xmlDoc).find('deviceName').eq(0).text() + '\r\n');
      arrStr.push('设备ID：' + $(xmlDoc).find('deviceID').eq(0).text() + '\r\n');
      arrStr.push('型号：' + $(xmlDoc).find('model').eq(0).text() + '\r\n');
      arrStr.push('设备序列号：' + $(xmlDoc).find('serialNumber').eq(0).text() + '\r\n');
      arrStr.push('MAC地址：' + $(xmlDoc).find('macAddress').eq(0).text() + '\r\n');
      arrStr.push(
        '主控版本：' +
          $(xmlDoc).find('firmwareVersion').eq(0).text() +
          ' ' +
          $(xmlDoc).find('firmwareReleasedDate').eq(0).text() +
          '\r\n',
      );
      arrStr.push(
        '编码版本：' +
          $(xmlDoc).find('encoderVersion').eq(0).text() +
          ' ' +
          $(xmlDoc).find('encoderReleasedDate').eq(0).text() +
          '\r\n',
      );

      showCBInfo(szDeviceIdentify + ' 获取设备信息成功！');
      ElMessage.success(arrStr.join(''));
    },
    error: function (oError) {
      showCBInfo(szDeviceIdentify + ' 获取设备信息失败！' + oError.errorMsg);
    },
  });
};

// 退出
export const clickLogout = (data) => {
  var szDeviceIdentify = `${data.ip}_${data.port}`;
  if (null == szDeviceIdentify) {
    return;
  }
  WebVideoCtrl.I_Logout(szDeviceIdentify).then(
    () => {
      showCBInfo(szDeviceIdentify + ' ' + '退出成功！');
    },
    () => {
      showCBInfo(szDeviceIdentify + ' ' + '退出失败！');
    },
  );
  //停止预览
  WebVideoCtrl.I_Stop({});
};

export const initChannelList = (data) => {
  if (data) {
    return getChannelInfo(`${data.ip}_${data.port}`);
  }
};

//  登录
export function login(data) {
  return new Promise((resolve, reject) => {
    try {
      if (data.ip === '') {
        reject(new Error('IP 不能为空'));
        return;
      }
      WebVideoCtrl.I_Login(data.ip, 1, data.port, data.userName, data.password, {
        success: function (xmlDoc) {
          resolve(xmlDoc);
        },
        error: function (error) {
          reject(error);
        },
      });
    } catch (error) {
      console.log('发生了一个错误，登录尝试失败。');
      reject(error);
    }
  });
}

// 获取通道
export function getChannelInfo(szDeviceIdentify) {
  return new Promise((resolve, reject) => {
    if (null == szDeviceIdentify) {
      reject(new Error('设备标识不能为空'));
      return;
    }
    let channelList = [];
    // 数字通道
    WebVideoCtrl.I_GetDigitalChannelInfo(szDeviceIdentify, {
      success: function (xmlDoc) {
        var oChannels = $(xmlDoc).find('InputProxyChannelStatus');
        $.each(oChannels, function (i) {
          var id = $(this).find('id').eq(0).text(),
            name = $(this).find('name').eq(0).text(),
            online = $(this).find('online').eq(0).text();
          if ('false' == online) {
            // 过滤禁用的数字通道
            return true;
          }
          if ('' == name) {
            name = 'IPCamera ' + (i < 9 ? '0' + (i + 1) : i + 1);
          }
          channels.push({
            value: id,
            label: name,
          });
          channelList.push({
            value: id,
            label: name,
          });
          channelValue.value = channels[0].value;
        });
        resolve(channelList);
        // showCBInfo(szDeviceIdentify + ' 获取数字通道成功！');
      },
      error: function (oError) {
        reject(oError);
        // showCBInfo(szDeviceIdentify + ' 获取数字通道失败！' + oError.errorMsg);
      },
    });
  });
}

// 获取端口
export const getDevicePort = (szDeviceIdentify) => {
  if (!szDeviceIdentify) {
    return;
  }
  console.log('szDeviceIdentify=================', szDeviceIdentify);
  WebVideoCtrl.I_GetDevicePort(szDeviceIdentify).then(
    (oPort) => {
      ElMessage.success('登录成功', oPort);
    },
    (oError) => {
      ElMessage.error(oError.errorMsg);
    },
  );
};
// 开始预览
export const startRealPlay = (data) => {
  console.log('g_iWndIndex', g_iWndIndex);
  var oWndInfo = WebVideoCtrl.I_GetWindowStatus(g_iWndIndex);
  console.log('oWndInfo', oWndInfo);
  var startRealPlay = function () {
    WebVideoCtrl.I_StartRealPlay(`${data.ip}_${data.port}`, {
      iStreamType: 1,
      iChannelID: channelValue.value, //播放通道
      bZeroChannel: false,
      iWndIndex: g_iWndIndex,
      success: function () {
        console.log(' 开始预览成功！');
      },
      error: function (oError) {
        console.log(' 开始预览失败！', oError.errorMsg);
        ElMessage.error('预览失败，请先登陆');
      },
    });
  };

  if (oWndInfo != null) {
    // 已经在播放了，先停止
    WebVideoCtrl.I_Stop({
      iWndIndex: g_iWndIndex,
      success: () => {
        startRealPlay();
      },
      error: function (oError) {
        showCBInfo('停止预览失败！', oError.errorMsg);
      },
    });
  } else {
    startRealPlay();
  }
};

// 停止预览
export const clickStopRealPlay = () => {
  var oWndInfo = WebVideoCtrl.I_GetWindowStatus(g_iWndIndex),
    szInfo = '';

  if (oWndInfo != null) {
    WebVideoCtrl.I_Stop({
      iWndIndex: g_iWndIndex,
      success: function () {
        szInfo = '停止预览成功！';
        showCBInfo(oWndInfo.szDeviceIdentify + ' ' + szInfo);
      },
      error: function (oError) {
        showCBInfo(szDeviceIdentify + ' 停止预览失败！' + oError.errorMsg);
      },
    });
  }
};

// 停止所有窗体预览
export const stopRealPlayByIndex = (wIndex) => {
  WebVideoCtrl.I_Stop({
    iWndIndex: wIndex,
    success: function () {},
    error: function (oError) {},
  });
};

//窗体隐藏
export const hideWindow = () => {
  try {
    WebVideoCtrl.I_HidPlugin();
  } catch (error) {
    console.log(error);
  }
};

export const showWindow = async () => {
  try {
    await WebVideoCtrl.I_ShowPlugin();
    return true;
  } catch (error) {
    console.log(error);
    return false;
  }
};

export const PTZZoomIn = () => {
  var oWndInfo = WebVideoCtrl.I_GetWindowStatus(g_iWndIndex);

  if (oWndInfo != null) {
    WebVideoCtrl.I_PTZControl(10, false, {
      iWndIndex: g_iWndIndex,
      success: function (xmlDoc) {
        showCBInfo(oWndInfo.szDeviceIdentify + ' 调焦变倍+成功！');
      },
      error: function (oError) {
        showCBInfo(oWndInfo.szDeviceIdentify + '  调焦变倍+失败！' + oError.errorMsg);
      },
    });
  }
};

export const PTZZoomout = () => {
  var oWndInfo = WebVideoCtrl.I_GetWindowStatus(g_iWndIndex);

  if (oWndInfo != null) {
    WebVideoCtrl.I_PTZControl(11, false, {
      iWndIndex: g_iWndIndex,
      success: function (xmlDoc) {
        showCBInfo(oWndInfo.szDeviceIdentify + ' 调焦变倍-成功！');
      },
      error: function (oError) {
        showCBInfo(oWndInfo.szDeviceIdentify + '  调焦变倍-失败！' + oError.errorMsg);
      },
    });
  }
};

export const PTZZoomStop = () => {
  var oWndInfo = WebVideoCtrl.I_GetWindowStatus(g_iWndIndex);

  if (oWndInfo != null) {
    WebVideoCtrl.I_PTZControl(11, true, {
      iWndIndex: g_iWndIndex,
      success: function (xmlDoc) {
        showCBInfo(oWndInfo.szDeviceIdentify + ' 调焦变倍停止成功！');
      },
      error: function (oError) {
        showCBInfo(oWndInfo.szDeviceIdentify + '  调焦变倍停止失败！' + oError.errorMsg);
      },
    });
  }
};

export const PTZFocusIn = () => {
  var oWndInfo = WebVideoCtrl.I_GetWindowStatus(g_iWndIndex);

  if (oWndInfo != null) {
    WebVideoCtrl.I_PTZControl(12, false, {
      iWndIndex: g_iWndIndex,
      success: function (xmlDoc) {
        showCBInfo(oWndInfo.szDeviceIdentify + ' 聚焦+成功！');
      },
      error: function (oError) {
        showCBInfo(oWndInfo.szDeviceIdentify + '  聚焦+失败！' + oError.errorMsg);
      },
    });
  }
};

export const PTZFoucusOut = () => {
  var oWndInfo = WebVideoCtrl.I_GetWindowStatus(g_iWndIndex);

  if (oWndInfo != null) {
    WebVideoCtrl.I_PTZControl(13, false, {
      iWndIndex: g_iWndIndex,
      success: function (xmlDoc) {
        showCBInfo(oWndInfo.szDeviceIdentify + ' 聚焦-成功！');
      },
      error: function (oError) {
        showCBInfo(oWndInfo.szDeviceIdentify + '  聚焦-失败！' + oError.errorMsg);
      },
    });
  }
};

export const PTZFoucusStop = () => {
  var oWndInfo = WebVideoCtrl.I_GetWindowStatus(g_iWndIndex);

  if (oWndInfo != null) {
    WebVideoCtrl.I_PTZControl(12, true, {
      iWndIndex: g_iWndIndex,
      success: function (xmlDoc) {
        showCBInfo(oWndInfo.szDeviceIdentify + ' 聚焦停止成功！');
      },
      error: function (oError) {
        showCBInfo(oWndInfo.szDeviceIdentify + '  聚焦停止失败！' + oError.errorMsg);
      },
    });
  }
};

export const PTZIrisIn = () => {
  var oWndInfo = WebVideoCtrl.I_GetWindowStatus(g_iWndIndex);

  if (oWndInfo != null) {
    WebVideoCtrl.I_PTZControl(14, false, {
      iWndIndex: g_iWndIndex,
      success: function (xmlDoc) {
        showCBInfo(oWndInfo.szDeviceIdentify + ' 光圈+成功！');
      },
      error: function (oError) {
        showCBInfo(oWndInfo.szDeviceIdentify + '  光圈+失败！' + oError.errorMsg);
      },
    });
  }
};

export const PTZIrisOut = () => {
  var oWndInfo = WebVideoCtrl.I_GetWindowStatus(g_iWndIndex);

  if (oWndInfo != null) {
    WebVideoCtrl.I_PTZControl(15, false, {
      iWndIndex: g_iWndIndex,
      success: function (xmlDoc) {
        showCBInfo(oWndInfo.szDeviceIdentify + ' 光圈-成功！');
      },
      error: function (oError) {
        showCBInfo(oWndInfo.szDeviceIdentify + '  光圈-失败！' + oError.errorMsg);
      },
    });
  }
};

export const PTZIrisStop = () => {
  var oWndInfo = WebVideoCtrl.I_GetWindowStatus(g_iWndIndex);

  if (oWndInfo != null) {
    WebVideoCtrl.I_PTZControl(14, true, {
      iWndIndex: g_iWndIndex,
      success: function (xmlDoc) {
        showCBInfo(oWndInfo.szDeviceIdentify + ' 光圈停止成功！');
      },
      error: function (oError) {
        showCBInfo(oWndInfo.szDeviceIdentify + '  光圈停止失败！' + oError.errorMsg);
      },
    });
  }
};

// 搜索录像
var g_iSearchTimes = 0;
export const clickRecordSearch = async (iType, data, iChannelID, iStreamType, startTime, endTime) => {
  if (!data.videoLogin) {
    return searchData;
  }
  var szDeviceIdentify = data.ip + '_' + data.port;
  if (Date.parse(endTime.replace(/-/g, '/')) - Date.parse(startTime.replace(/-/g, '/')) < 0) {
    alert('开始时间大于结束时间');
    return;
  }
  if (null == szDeviceIdentify) {
    return;
  }
  if (0 == iType) {
    // 首次搜索
    searchData.length = 0;
    g_iSearchTimes = 0;
  }
  //如果是前端设备，需要将搜索时间转换为UTC时间
  await WebVideoCtrl.I_RecordSearch(szDeviceIdentify, iChannelID, startTime, endTime, {
    iStreamType: iStreamType,
    iSearchPos: g_iSearchTimes,
    success: function (xmlDoc) {
      if ('MORE' === $(xmlDoc).find('responseStatusStrg').eq(0).text()) {
        for (var i = 0, nLen = $(xmlDoc).find('searchMatchItem').length; i < nLen; i++) {
          var szPlaybackURI = $(xmlDoc).find('playbackURI').eq(i).text();
          if (szPlaybackURI.indexOf('name=') < 0) {
            break;
          }
          var localStartTime = $(xmlDoc).find('startTime').eq(i).text();
          var localEndTime = $(xmlDoc).find('endTime').eq(i).text();
          var fileName =
            'T_' +
            szPlaybackURI.substring(szPlaybackURI.indexOf('name=') + 5, szPlaybackURI.indexOf('&size=')) +
            '.mp4';
          var size = szPlaybackURI.substring(szPlaybackURI.indexOf('size=') + 5, szPlaybackURI.length);
          ++g_iSearchTimes;
          searchData.push({
            startTime,
            endTime,
            fileName,
            szPlaybackURI,
            size,
            times: g_iSearchTimes,
          });
        }

        clickRecordSearch(1, data, iChannelID, iStreamType, localStartTime, localEndTime); // 继续搜索
      } else if ('OK' === $(xmlDoc).find('responseStatusStrg').eq(0).text()) {
        var iLength = $(xmlDoc).find('searchMatchItem').length;
        for (var i = 0; i < iLength; i++) {
          var szPlaybackURI = $(xmlDoc).find('playbackURI').eq(i).text();
          if (szPlaybackURI.indexOf('name=') < 0) {
            break;
          }
          var startTime = $(xmlDoc).find('startTime').eq(i).text();
          var endTime = $(xmlDoc).find('endTime').eq(i).text();
          var fileName =
            'T_' +
            szPlaybackURI.substring(szPlaybackURI.indexOf('name=') + 5, szPlaybackURI.indexOf('&size=')) +
            '.mp4';
          var size = szPlaybackURI.substring(szPlaybackURI.indexOf('size=') + 5, szPlaybackURI.length);
          ++g_iSearchTimes;
          searchData.push({
            startTime,
            endTime,
            fileName,
            szPlaybackURI,
            size,
            times: g_iSearchTimes,
          });
        }
        showCBInfo(szDeviceIdentify + ' 搜索录像文件成功！');
      } else if ('NO MATCHES' === $(xmlDoc).find('responseStatusStrg').eq(0).text()) {
        setTimeout(function () {
          g_iSearchTimes = 0;
          showCBInfo(szDeviceIdentify + ' 没有录像文件！');
        }, 50);
      }
    },
    error: function (oError) {
      g_iSearchTimes = 0;
      searchData.length = 0;
      showCBInfo(szDeviceIdentify + ' 搜索录像文件失败！' + oError.errorMsg);
    },
  });
  return searchData;
};

//开始回放
export const clickStartPlayback = async (data, szStartTime, szEndTime, iChannelID, iStreamType, bChecked) => {
  if (!data.videoLogin) {
    showCBInfo('回放失败，设备未登录');
    return;
  }
  var oWndInfo = WebVideoCtrl.I_GetWindowStatus(g_iWndIndex),
    szDeviceIdentify = data.ip + '_' + data.port,
    szInfo = '',
    bZeroChannel = false;

  if (null == szDeviceIdentify) {
    return;
  }

  if (bZeroChannel) {
    // 零通道不支持回放
    return;
  }

  var startPlayback = function () {
    if (bChecked) {
      // 启用转码回放
      var oTransCodeParam = {
        TransFrameRate: '14', // 0：全帧率，5：1，6：2，7：4，8：6，9：8，10：10，11：12，12：16，14：15，15：18，13：20，16：22
        TransResolution: '1', // 255：Auto，3：4CIF，2：QCIF，1：CIF
        TransBitrate: '19', // 2：32K，3：48K，4：64K，5：80K，6：96K，7：128K，8：160K，9：192K，10：224K，11：256K，12：320K，13：384K，14：448K，15：512K，16：640K，17：768K，18：896K，19：1024K，20：1280K，21：1536K，22：1792K，23：2048K，24：3072K，25：4096K，26：8192K
      };
      WebVideoCtrl.I_StartPlayback(szDeviceIdentify, {
        iStreamType: iStreamType,
        iWndIndex: g_iWndIndex,
        iChannelID: iChannelID,
        szStartTime: szStartTime,
        szEndTime: szEndTime,
        oTransCodeParam: oTransCodeParam,
        success: function () {
          szInfo = '开始回放成功！';
          showCBInfo(szDeviceIdentify + ' ' + szInfo);
        },
        error: function (oError) {
          szInfo = '开始回放失败！';
          showCBInfo(szDeviceIdentify + szInfo + oError.errorMsg);
        },
      });
    } else {
      WebVideoCtrl.I_StartPlayback(szDeviceIdentify, {
        iStreamType: iStreamType,
        iChannelID: iChannelID,
        szStartTime: szStartTime,
        iWndIndex: g_iWndIndex,
        szEndTime: szEndTime,
        success: function () {
          szInfo = '开始回放成功！';
          showCBInfo(szDeviceIdentify + ' ' + szInfo);
        },
        error: function (oError) {
          szInfo = '开始回放失败！';
          showCBInfo(szDeviceIdentify + szInfo + oError.errorMsg);
        },
      });
    }
  };

  if (oWndInfo != null) {
    // 已经在播放了，先停止
    WebVideoCtrl.I_Stop({
      success: async function () {
        await startPlayback();
      },
    });
  } else {
    await startPlayback();
  }
};

//获取当前窗口
export const getCurWindowIndex = () => {
  return g_iWndIndex;
};

//获取所有窗口index
export const getAllWindowIndex = () => {
  return uniqueNumbers;
};

export function retCurWindowIndex() {
  g_iWndIndex = 0;
}

//获取当前窗口
export const getWebVideoCtrl = () => {
  return WebVideoCtrl;
};

// 停止回放
export const clickStopPlayback = (data) => {
  if (!data.videoLogin) {
    showCBInfo('停止回放失败，设备未登录');
    return;
  }
  var oWndInfo = WebVideoCtrl.I_GetWindowStatus(g_iWndIndex),
    szInfo = '';

  if (oWndInfo != null) {
    WebVideoCtrl.I_Stop({
      iWndIndex: g_iWndIndex,
      success: function () {
        szInfo = '停止回放成功！';
        showCBInfo(oWndInfo.szDeviceIdentify + ' ' + szInfo);
      },
      error: function (oError) {
        szInfo = '停止回放失败！';
        showCBInfo(szDeviceIdentify + szInfo + oError.errorMsg);
      },
    });
  }
};

// 开始倒放
export const clickReversePlayback = (data, szStartTime, szEndTime, iChannelID, iStreamType) => {
  if (!data.videoLogin) {
    showCBInfo('开始倒放失败，设备未登录');
    return;
  }
  var oWndInfo = WebVideoCtrl.I_GetWindowStatus(g_iWndIndex),
    szDeviceIdentify = data.ip + '_' + data.port,
    bZeroChannel = false,
    szInfo = '';

  if (null == szDeviceIdentify) {
    return;
  }

  if (bZeroChannel) {
    // 零通道不支持倒放
    return;
  }

  var reversePlayback = function () {
    WebVideoCtrl.I_ReversePlayback(szDeviceIdentify, {
      iStreamType: iStreamType,
      iChannelID: iChannelID,
      iWndIndex: g_iWndIndex,
      szStartTime: szStartTime,
      szEndTime: szEndTime,
    }).then(
      () => {
        szInfo = '开始倒放成功！';
        showCBInfo(szDeviceIdentify + ' ' + szInfo);
      },
      (oError) => {
        szInfo = '开始倒放失败！';
        showCBInfo(szDeviceIdentify + szInfo + oError.errorMsg);
      },
    );
  };

  if (oWndInfo != null) {
    // 已经在播放了，先停止
    WebVideoCtrl.I_Stop({
      success: function () {
        reversePlayback();
      },
    });
  } else {
    reversePlayback();
  }
};

// 单帧
export const clickFrame = (data) => {
  if (!data.videoLogin) {
    showCBInfo('单帧失败，设备未登录');
    return;
  }
  var oWndInfo = WebVideoCtrl.I_GetWindowStatus(g_iWndIndex),
    szInfo = '';

  if (oWndInfo != null) {
    WebVideoCtrl.I_Frame({
      iWndIndex: g_iWndIndex,
      success: function () {
        szInfo = '单帧播放成功！';
        showCBInfo(oWndInfo.szDeviceIdentify + ' ' + szInfo);
      },
      error: function (oError) {
        szInfo = '单帧播放失败！';
        showCBInfo(oWndInfo.szDeviceIdentify + szInfo + oError.errorMsg);
      },
    });
  }
};

// 暂停
export const clickPause = (data) => {
  if (!data.videoLogin) {
    showCBInfo('暂停失败，设备未登录');
    return;
  }
  var oWndInfo = WebVideoCtrl.I_GetWindowStatus(g_iWndIndex),
    szInfo = '';

  if (oWndInfo != null) {
    WebVideoCtrl.I_Pause({
      iWndIndex: g_iWndIndex,
      success: function () {
        szInfo = '暂停成功！';
        showCBInfo(oWndInfo.szDeviceIdentify + ' ' + szInfo);
      },
      error: function (oError) {
        szInfo = '暂停失败！';
        showCBInfo(oWndInfo.szDeviceIdentify + szInfo + oError.errorMsg);
      },
    });
  }
};

// 恢复
export const clickResume = (data) => {
  if (!data.videoLogin) {
    showCBInfo('恢复失败，设备未登录');
    return;
  }
  var oWndInfo = WebVideoCtrl.I_GetWindowStatus(g_iWndIndex),
    szInfo = '';

  if (oWndInfo != null) {
    WebVideoCtrl.I_Resume({
      iWndIndex: g_iWndIndex,
      success: function () {
        szInfo = '恢复成功！';
        showCBInfo(oWndInfo.szDeviceIdentify + ' ' + szInfo);
      },
      error: function (oError) {
        szInfo = '恢复失败！';
        showCBInfo(oWndInfo.szDeviceIdentify + szInfo);
      },
    });
  }
};

// 慢放
export const clickPlaySlow = (data) => {
  if (!data.videoLogin) {
    showCBInfo('慢放失败，设备未登录');
    return;
  }
  var oWndInfo = WebVideoCtrl.I_GetWindowStatus(g_iWndIndex),
    szInfo = '';

  if (oWndInfo != null) {
    WebVideoCtrl.I_PlaySlow({
      iWndIndex: g_iWndIndex,
      success: function () {
        szInfo = '慢放成功！';
        showCBInfo(oWndInfo.szDeviceIdentify + ' ' + szInfo);
      },
      error: function (oError) {
        szInfo = '慢放失败！';
        showCBInfo(oWndInfo.szDeviceIdentify + szInfo + oError.errorMsg);
      },
    });
  }
};

// 快放
export const clickPlayFast = (data) => {
  if (!data.videoLogin) {
    showCBInfo('快放失败，设备未登录');
    return;
  }
  var oWndInfo = WebVideoCtrl.I_GetWindowStatus(g_iWndIndex),
    szInfo = '';

  if (oWndInfo != null) {
    WebVideoCtrl.I_PlayFast({
      iWndIndex: g_iWndIndex,
      success: function () {
        szInfo = '快放成功！';
        showCBInfo(oWndInfo.szDeviceIdentify + ' ' + szInfo);
      },
      error: function (oError) {
        szInfo = '快放失败！';
        showCBInfo(oWndInfo.szDeviceIdentify + szInfo + oError.errorMsg);
      },
    });
  }
};

// 开始录像
var g_szRecordType = '';
export const clickStartRecord = async (data, szType) => {
  if (!data.videoLogin) {
    showCBInfo('开始剪辑失败，设备未登录');
    return;
  }
  var oWndInfo = WebVideoCtrl.I_GetWindowStatus(g_iWndIndex),
    szInfo = '';

  g_szRecordType = szType;
  console.log(g_iWndIndex);
  console.log(oWndInfo);
  let szFileName = '';
  if (oWndInfo != null) {
    szFileName =
      'T_' + dateFormat(new Date(), 'yyyy-MM-dd hh:mm:ss').replace(/-/g, '').replace(/:/g, '').replace(/\s/g, '');
    await WebVideoCtrl.I_StartRecord(szFileName, {
      bDateDir: false, //是否生成日期文件
      iWndIndex: g_iWndIndex,
      success: function () {
        if ('realplay' === szType) {
          szInfo = '开始录像成功！';
        } else if ('playback' === szType) {
          szInfo = '开始剪辑成功！';
        }
        showCBInfo(oWndInfo.szDeviceIdentify + ' ' + szInfo);
      },
      error: function (oError) {
        if ('realplay' === szType) {
          szInfo = ' 开始录像失败！';
        } else if ('playback' === szType) {
          szInfo = ' 开始剪辑失败！';
        }
        szFileName = '';
        showCBInfo(oWndInfo.szDeviceIdentify + szInfo + oError.errorMsg);
      },
    });
  }

  return szFileName;
};

// 停止录像
export const clickStopRecord = async (data, szType, iWndIndex) => {
  if (!data.videoLogin) {
    showCBInfo('停止剪辑失败，设备未登录');
    return;
  }
  if ('undefined' === typeof iWndIndex) {
    iWndIndex = g_iWndIndex;
  }
  var oWndInfo = WebVideoCtrl.I_GetWindowStatus(iWndIndex),
    szInfo = '';

  if (oWndInfo != null) {
    await WebVideoCtrl.I_StopRecord({
      iWndIndex: g_iWndIndex,
      success: function () {
        if ('realplay' === szType) {
          szInfo = '停止录像成功！';
        } else if ('playback' === szType) {
          szInfo = '停止剪辑成功！';
        }
        showCBInfo(oWndInfo.szDeviceIdentify + ' ' + szInfo);
      },
      error: function (oError) {
        if ('realplay' === szType) {
          szInfo = '停止录像失败！';
        } else if ('playback' === szType) {
          szInfo = '停止剪辑失败！';
        }
        showCBInfo(oWndInfo.szDeviceIdentify + szInfo + oError.errorMsg);
      },
    });
  }
};

// 下载录像
var g_iDownloadID = -1;
var g_tDownloadProcess = 0;
export const clickStartDownloadRecord = async (data, szFileName, szPlaybackURI) => {
  if (!data.videoLogin) {
    showCBInfo('下载录像失败，设备未登录');
    return;
  }
  var szDeviceIdentify = data.ip + '_' + data.port;
  await WebVideoCtrl.I_StartDownloadRecord(szDeviceIdentify, szPlaybackURI, szFileName, {
    bDateDir: true, //是否生成日期文件
  }).then(
    (iDownloadID) => {
      g_iDownloadID = iDownloadID;
      g_tDownloadProcess = setInterval(downProcess, 1000); //定时器
    },
    (oError) => {
      WebVideoCtrl.I_GetLastError().then((iErrorValue) => {
        if (34 == iErrorValue) {
          showCBInfo(szDeviceIdentify + ' 已下载！');
        } else if (33 == iErrorValue) {
          showCBInfo(szDeviceIdentify + ' 空间不足！');
        } else {
          showCBInfo(szDeviceIdentify + ' 下载失败！');
        }
      });
    },
  );
};

// 下载进度
export const downProcess = async () => {
  var iStatus = await WebVideoCtrl.I_GetDownloadStatus(g_iDownloadID);
  if (0 == iStatus) {
    var iProcess = await WebVideoCtrl.I_GetDownloadProgress(g_iDownloadID);
    percentage.value = iProcess;
    if (iProcess < 0) {
      clearInterval(g_tDownloadProcess); //清除定时器
      g_tDownloadProcess = 0;
      g_iDownloadID = -1;
    } else if (iProcess < 100) {
      console.log('下载进度：' + iProcess);
    } else {
      await WebVideoCtrl.I_StopDownloadRecord(g_iDownloadID);
      showCBInfo('录像下载完成！');
      clearInterval(g_tDownloadProcess); //清除定时器
      g_tDownloadProcess = 0;
      g_iDownloadID = -1;
    }
  } else {
    await WebVideoCtrl.I_StopDownloadRecord(g_iDownloadID);
    clearInterval(g_tDownloadProcess); //清除定时器
    g_tDownloadProcess = 0;
    g_iDownloadID = -1;
  }
  return iProcess;
};

//停止下载
export const clickStopDownload = (data) => {
  szDeviceIdentify = data.ip + '_' + data.port;
  WebVideoCtrl.I_StopDownloadRecord(g_iDownloadID).then(
    () => {
      showCBInfo('停止下载成功！');
      clearInterval(g_tDownloadProcess);
      g_tDownloadProcess = 0;
      g_iDownloadID = -1;
    },
    (oError) => {
      showCBInfo(szDeviceIdentify + ' 停止下载失败！' + oError.errorMsg);
    },
  );
};

//按时间下载
export const clickStartDownloadRecordByTime = async (data, szFileName, szPlaybackURI, szStartTime, szEndTime) => {
  if (!data.videoLogin) {
    showCBInfo('下载录像失败，设备未登录');
    return;
  }

  if (Date.parse(szEndTime.replace(/-/g, '/')) - Date.parse(szStartTime.replace(/-/g, '/')) < 0) {
    showCBInfo('开始时间大于结束时间');
    return;
  }
  let szDeviceIdentify = data.ip + '_' + data.port;
  console.log('szDeviceIdentify', szDeviceIdentify, szStartTime, szEndTime);
  await WebVideoCtrl.I_StartDownloadRecordByTime(szDeviceIdentify, szPlaybackURI, szFileName, szStartTime, szEndTime, {
    bDateDir: true, //是否生成日期文件
  }).then(
    (iDownloadID) => {
      g_iDownloadID = iDownloadID;
      g_tDownloadProcess = setInterval(downProcess, 1000);
    },
    (oError) => {
      console.log(oError);
      showCBInfo(szDeviceIdentify + ' 下载失败！' + oError.errorMsg);
    },
  );
};

// 打开选择框 0：文件夹  1：文件
export const clickOpenFileDlg = async (iType) => {
  let DirPath = '';
  await WebVideoCtrl.I_OpenFileDlg(iType).then(
    function (szDirPath) {
      if (szDirPath != -1 && szDirPath != '' && szDirPath != null) {
        DirPath = szDirPath;
      }
    },
    function () {
      showCBInfo('打开文件路径失败');
      return '';
    },
  );
  return DirPath;
};

// 获取OSD时间
export const clickGetOSDTime = (iWndIndex) => {
  var oWndInfo = WebVideoCtrl.I_GetWindowStatus(iWndIndex);
  var szOSDTime = '';
  if (oWndInfo != null) {
    szOSDTime = WebVideoCtrl.I_GetOSDTime({
      iWndIndex: g_iWndIndex,
      success: function (szOSDTime) {
        szOSDTime = szOSDTime;
      },
      error: function (oError) {},
    });
  }
  return szOSDTime;
};

let g_oLocalConfig = null;
// 获取本地参数
export const clickGetLocalCfg = async () => {
  await WebVideoCtrl.I_GetLocalCfg().then(
    (oLocalConfig) => {
      g_oLocalConfig = oLocalConfig;
      // showCBInfo('本地配置获取成功！');
    },
    (oError) => {
      // var szInfo = '本地配置获取失败！';
      // showCBInfo(szInfo, oError.errorCode, oError.errorMsg);
    },
  );
  return g_oLocalConfig;
};

// 设置本地参数
export const clickSetLocalCfg = (oLocalConfig) => {
  WebVideoCtrl.I_SetLocalCfg(oLocalConfig).then(
    () => {
      // showCBInfo('本地配置设置成功！');
    },
    (oError) => {
      // var szInfo = '本地配置设置失败！';
      // showCBInfo(szInfo + oError.errorMsg);
    },
  );
};
